import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:yt_devops/components/log_utils.dart';

import 'db_manager.dart';

///
/// @Description TODO
/// @Author liuer
/// @CreateTime 2023年11月23日 08:52
enum LogType{
  error,//错误日志
  business,//业务日志
  network//网络请求日志
}
class MyErrorsHandler{
  ///widget错误
  static widgetErrorDetails(FlutterErrorDetails details){
    Log.d('==FlutterErrorDetails==$details');
    saveErrorData('widgetErrorDetails',details.toString());
  }
  ///未被 Flutter 捕获的错误,例如 MethodChannel.invokeMethod （或者其他 plugin 的方法）
  static platformError(Object exception, StackTrace stackTrace){
    Log.d('==onError==$stackTrace');
    saveErrorData('platformError',exception.toString() + stackTrace.toString());
  }
  ///isolateError
  static isolateError(Function? handler){
    Log.d('==isolateError==$handler');
    saveErrorData('isolateError',handler.toString());
  }
  ///保存错误数据
  static saveErrorData(String errorType,String errorString) async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    var mobileName = '';
    var systemVersion = '';
    var systemType = '';
    if(TargetPlatform.android == defaultTargetPlatform){
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      mobileName = '${androidInfo.manufacturer}-${androidInfo.model}${androidInfo.version.release}';
      systemVersion = androidInfo.version.release;
      systemType = 'Android';
    }
    if(TargetPlatform.iOS == defaultTargetPlatform){
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      mobileName = iosInfo.utsname.machine;
      systemVersion = iosInfo.systemVersion;
      systemType = 'iOS';
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    DateTime now = DateTime.now();
    Log.d('LogType==' + LogType.error.toString());
    var map = {
      'logType':LogType.error.toString(),//日志类型:包括错误日志,业务日志,网络请求日志
      'logLevel':1,//日志优先级
      'isUpload':false,//日志是否已经上传
      'mobileName':mobileName,//手机型号
      'systemVersion':systemVersion,//系统版本
      'appVersion':packageInfo.version??'',//app版本
      'systemType':systemType,//系统类型,iOS或者Android
      'errorType':errorType,//错误类型:widget错误,数据类型或者原生错误,或者isolateError
      'errorString':errorString,//错误具体内容
      'currentRoute':Get.currentRoute.toString(),//当前路由
      'timeDate':now.toString(),//当前时间
      'timeStamp':now.millisecondsSinceEpoch,//当前时间戳,毫秒,用做唯一标识
    };
    Log.d('map======' + map.toString());
    int result = await DBManager().saveData(map);
    if (result > 0) {
      Log.d('保存数据成功，result:$result');
    } else {
      Log.d('保存数据失败，result:$result');
    }
  }
}